<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Tree;
use think\Cookie;
use think\Hook;

class Cart extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'mall';

    public function _initialize()
    {
        parent::_initialize();

        //获取brand BEGIN
        $mapBrand = [
            'switch' => 1,
        ];
        $brandData = model('app\common\model\Brand')
            ->field('id,name,image')
            ->where($mapBrand)
            ->order('top_switch desc,weigh asc')
            ->select();

        //$brand = addWebSiteUrl($brandData, ['image']);
        $this->view->assign('brand',$brandData);
        //获取brand END

        //cart BEGIN
        $cart = Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];
        $this->view->assign('cart',$cart);
        //cart END

        //获取商品cate BEGIN
        $tree = Tree::instance();
        $tree->init(collection( model('app\common\model\Category')->where('type','goods')->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $category = $tree->getTreeArray(0);
        $this->view->assign('category',$category);
        //获取商品cate END

    }

    public function index()
    {
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $products_id = $this->request->post('products_id');
            $num = $this->request->post('num');

            $cart = Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];
            $expire = 0;

            $result = model('app\common\model\Products')->getProductInfo($products_id);
            $data = $result['data'];
            if (!$data) $this->error();

            $curr_num = isset($cart[$products_id]['num']) ? $num + $cart[$products_id]['num'] : $num;
            $cart[$products_id] = [
                'products_id' => $products_id,
                'num' => $curr_num,
                'name' => $data['goods']['name'],
                'image' => $data['image'],
                'price' => $data['price'],
            ];

            Cookie::set('mall_cart', json_encode($cart), $expire);
            $this->success('Add Success','',$cart);
        }
    }

    public function getCarts()
    {
        return Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];
    }

    public function del()
    {
        $products_id = $this->request->request('products_id');

        $cart = Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];
        $expire = 0;

        if ($cart[$products_id]){
            unset($cart[$products_id]);
        }

        Cookie::set('mall_cart', json_encode($cart), $expire);

        $this->success();
    }


}
